<?php

namespace App\Http\Controllers;

use App\Common\Curl;
use App\Http\Controllers\Traits\TransFormer;
use App\Http\Requests\MessRequest;
use App\Models\Patient;
use App\Services\PatientService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class PatientController extends Controller
{
    use TransFormer;

    protected $service;
    protected $mess;
    protected $upload;
    public function __construct(PatientService $service,MessRequest $mess,UploadController $upload)
    {
        $this->service = $service;
        $this->mess = $mess;
        $this->upload = $upload;
    }

    public function create(Request $request)
    {
        $data = $request->all();
        $rules = $this->mess->create();
        $validator = Validator::make($data,$rules['rules'],[],$rules['rName']);
        if($validator -> fails()){
            return $this->transFormer(1001001,$validator->errors()->first());
        }
        $result = $this->service->create($data);
        return $this->transFormer(200,'成功',['patient_id'=>$result]);
    }

    /**
     * 获取ICD
     * @param Request $request
     * @return array
     */
    public function getIcdInfo(Request $request)
    {
        $data = $request->all();
        $rules = $this->mess->oneString();
        $validator = Validator::make($data,$rules['rules'],[],$rules['rName']);
        if($validator -> fails()){
            return $this->transFormer(1001004,$validator->errors()->first());
        }
        $res = DB::table('icd10')->where('name','like','%'.$data['name'].'%')->take(50)->get();
        if ($res->isNotEmpty()) {
            return $this->transFormer(200,'成功',$res);
        } else {
            return $this->transFormer(1001005,'未找到诊断信息');
        }
    }

    /**
     * 获取省份
     * @param Request $request
     * @return array
     */
    public function getProvince(Request $request)
    {
        $res = DB::table('province')->get();
        return $this->transFormer(200,'成功',$res);
    }

    /**
     * 获取市  根据 province_id
     * @param Request $request
     * @return array
     */
    public function getCity(Request $request)
    {
        $data = $request->all();
        $rules = $this->mess->getCity();
        $validator = Validator::make($data,$rules['rules'],[],$rules['rName']);
        if($validator -> fails()){
            return $this->transFormer(1001006,$validator->errors()->first());
        }
        $res = DB::table('city')->where('province_id',$data['province_id'])->get();
        if ($res->isNotEmpty()) {
            return $this->transFormer(200,'成功',$res);
        } else {
            return $this->transFormer(1001007,'未找到城市信息');
        }
    }

    /**
     * 获取地区
     * @param Request $request
     * @return array
     */
    public function getArea(Request $request)
    {
        $data = $request->all();
        $rules = $this->mess->getArea();
        $validator = Validator::make($data,$rules['rules'],[],$rules['rName']);
        if($validator -> fails()){
            return $this->transFormer(1001008,$validator->errors()->first());
        }
        $res = DB::table('area')->where('city_id',$data['city_id'])->get();
        if ($res->isNotEmpty()) {
            return $this->transFormer(200,'成功',$res);
        } else {
            return $this->transFormer(1001009,'未找到地区信息');
        }
    }

    /**
     * 身份证识别
     */
    public function idCodeocr(Request $request)
    {
        // img 需要 传 base64 信息
        $img = $request->img;
        if (empty($img)) {
            return $this->transFormer(1001012,'图像信息不存在');
        }
        //$base64_img = $img;
        $url = "http://idcodeocr.market.alicloudapi.com/idcodeocr";
        $appcode = "a29e7d2d97e04de499caeb88aca6991d";
        $headers = array(
            "Authorization:APPCODE a29e7d2d97e04de499caeb88aca6991d",
            "Content-Type:application/x-www-form-urlencoded;charset=UTF-8"
        );

        //根据API的要求，定义相对应的Content-Type
        $bodys = "img=".urlencode($img)."&side=front";
        $curl_res = Curl::requestData($url, 'POST',$bodys,$headers);
        $info = json_decode($curl_res,true);

        if ($info['ret'] != 200) {
            return $this->transFormer(1001010,'身份证识别错误',$info);
        }

        $data = array(
            'patient_name' => $info['data']['info']['name'],
            'age' => $info['data']['info']['age'],
            'nation' => $info['data']['info']['nation'],
            'gender' => $info['data']['info']['sex'] == '男'? 1 : ($info['data']['info']['sex'] == '女' ? 2 : 0),
            'IDCard_number' => $info['data']['info']['idcard'],
            'IDCard_detail_address' => $info['data']['info']['address'],
            'province_name' => $info['data']['info']['birth_prov'],
            'city_name' => $info['data']['info']['birth_city'],
            'area_name' => $info['data']['info']['birth_region']
        );

        return $this->transFormer(200,'成功',$data);
    }

    /**
     * 获取患者详情
     * @param Request $request
     * @return array
     */
    public function getPatientInfo(Request $request)
    {
        $data = $request->all();
        $rules = $this->mess->patientId();
        $validator = Validator::make($data,$rules['rules'],[],$rules['rName']);
        if($validator -> fails()){
            return $this->transFormer(1001011,$validator->errors()->first());
        }
        $res = $this->service->getPatientInfo($data);
        return $this->transFormer(200,'成功',$res);
    }

    /**
     * 身份证识别 来自上传后识别
     * @param Request $request
     * @return array
     */
    public function idCodeFromUpload(Request $request)
    {
        $uploadArr = $this->upload->upload($request); // 上传
        $url = 'upload/'.$uploadArr['data']['url'];   // 获取路径
        $db = file_get_contents($url);                // 获取图片信息
        $img = 'data:image/jpg;base64,'.base64_encode($db);    // 转换
        if (empty($img)) {
            return $this->transFormer(1001012,'图像信息不存在');
        }

        $url = "http://idcodeocr.market.alicloudapi.com/idcodeocr";
        $appcode = "a29e7d2d97e04de499caeb88aca6991d";
        $headers = array(
            "Authorization:APPCODE a29e7d2d97e04de499caeb88aca6991d",
            "Content-Type:application/x-www-form-urlencoded;charset=UTF-8"
        );

        //根据API的要求，定义相对应的Content-Type
        $bodys = "img=".urlencode($img)."&side=front";
        $curl_res = Curl::requestData($url, 'POST',$bodys,$headers);
        $info = json_decode($curl_res,true);

        if ($info['ret'] != 200) {
            return $this->transFormer(1001010,'身份证识别错误',$info);
        }

        $data = array(
            'patient_name' => $info['data']['info']['name'],
            'age' => $info['data']['info']['age'],
            'nation' => $info['data']['info']['nation'],
            'gender' => $info['data']['info']['sex'] == '男'? 1 : ($info['data']['info']['sex'] == '女' ? 2 : 0),
            'IDCard_number' => $info['data']['info']['idcard'],
            'IDCard_detail_address' => $info['data']['info']['address'],
            'province_name' => $info['data']['info']['birth_prov'],
            'city_name' => $info['data']['info']['birth_city'],
            'area_name' => $info['data']['info']['birth_region']
        );

        return $this->transFormer(200,'成功',$data);
    }

    /**
     * 获取患者列表---带搜索
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function getPatientList(Request $request)
    {
        $patient_name = $request->patient_name;
        $event_id = $request->event_id;
        $level_id = $request->level_id;
        $sort = $request->sort;
        $page = $request->page;
        $limit = $request->limit;

        $where = array(
            'patient_name' => $patient_name,
            'event_id' => $event_id,
            'level_id' => $level_id,
            'sort' => $sort,
            'limit' => $limit,
            'page' => $page
        );
        $res = $this->service->getPatientList($where);
        return $this->transFormer(200,'成功',$res);
    }

}
